const express = require('express');
const router = express.Router();
const { Parent_comments  ,Sub_comments } = require('../models');
const { Op } = require('sequelize');
const { NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');


/**
 * 查询评论列表
 * GET /admin/articles
 */
router.get('/', async function (req, res) {

    try {
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        };

        const { count, rows } = await Parent_comments.findAndCountAll(condition);
        const sub = await Sub_comments.findAndCountAll(condition);
        const comments1 = rows
        const comments2 = sub.rows
        const data = []
        comments1.forEach(comment1 => {
            // 创建一个对象，用于存储主评论及其子评论
            let mergedComment = {
                comment: comment1, // 存储主评论的内容
                comment_sub: []    // 存储对应的子评论
            };

            // 遍历 comments2，找出与当前主评论关联的子评论
            comments2.forEach(comment2 => {
                if (comment2.reviewers_id === comment1.id) {
                    mergedComment.comment_sub.push(comment2);
                }
            });

            // 将完整的主评论及其子评论对象推入最终结果数组中
            data.push(mergedComment);
        });

        success(res, '查询评论列表成功。', {
            data,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});
router.get('/:id', async function (req, res) {

    try {
        // const postid = req.pa
        const {id} = req.params
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        };
        if (id) {
            condition.where = {
                postid: {
                    [Op.eq]: `${id}`
                }
            };
        }

        const { count, rows } = await Parent_comments.findAndCountAll(condition);
        const sub = await Sub_comments.findAndCountAll(condition);
        const comments1 = rows
        const comments2 = sub.rows
        const data = []
        comments1.forEach(comment1 => {
            // 创建一个对象，用于存储主评论及其子评论
            let mergedComment = {
                comment: comment1, // 存储主评论的内容
                comment_sub: []    // 存储对应的子评论
            };

            // 遍历 comments2，找出与当前主评论关联的子评论
            comments2.forEach(comment2 => {
                if (comment2.reviewers_id === comment1.id) {
                    mergedComment.comment_sub.push(comment2);
                }
            });

            // 将完整的主评论及其子评论对象推入最终结果数组中
            data.push(mergedComment);
        });

        success(res, '查询评论列表成功。', {
            data,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});


router.get('/parent', async function (req, res) {

    try {
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        };

        if (query.postid) {
            condition.where = {
                postid: {
                    [Op.eq]: `${query.postid}`
                }
            };  
        }
        
        const { count, rows } = await Parent_comments.findAndCountAll(condition);

        success(res, '查询评论列表成功。', {
            comment:rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});
/**
/**
 * 创建评论
 * POST /admin/articles
 */
router.post('/', async function (req, res) {
    try {
        const body = filterBody(req);
        body.publisher_id = req.user.id;
        if (!body.reviewers_id) {
            const parent_comments = await Parent_comments.create(body);
            success(res, '创建评论成功。', { parent_comments }, 201);
        } else {
            const sub_comments = await Sub_comments.create(body);
            success(res, '创建子评论成功。', { sub_comments }, 201);
        }
    } catch (error) {
        failure(res, error);
    }
});

/**



/**
 * 公共方法：查询当前评论
 */
// async function getParent_comments(req) {
//     const body = req.params;

//     const parent_comments = await Parent_comments.findByPk(body.id);
//     if (!parent_comments) {
//         throw new NotFoundError(`ID: ${id}的评论未找到。`)
//     }

//     return parent_comments;
// }

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
    return {
        id: req.body.id,
        postid: req.body.postid,
        userid: req.body.userid,//评论人
        content: req.body.content,
        image_url: req.body.image_url,
        content: req.body.content,
        like: req.body.like,
        // 子评论
        reviewers_id: req.body.reviewers_id//父评论id
    };
}

module.exports = router;
